define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'food/dish/index' + location.search,
                    add_url: 'food/dish/add',
                    edit_url: 'food/dish/edit',
                    del_url: 'food/dish/del',
                    multi_url: 'food/dish/multi',
                    import_url: 'food/dish/import',
                    table: 'food_dish',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'dish_type', title: __('Dish_type'), searchList: {"1":__('Dish_type 1'),"2":__('Dish_type 2'),"3":__('Dish_type 3'),"4":__('Dish_type 4'),"5":__('Dish_type 5'),"6":__('Dish_type 6')}, formatter: Table.api.formatter.normal},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'cook_time', title: __('Cook_time'), operate: 'LIKE'},
                        {field: 'difficulty', title: __('Difficulty'), searchList: {"1":__('Difficulty 1'),"2":__('Difficulty 2'),"3":__('Difficulty 3')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {
                            field: 'has_zero_ingredient', 
                            title: '缺少食材', 
                            formatter: function (value, row, index) {
                                // 如果有ingredient_id为0的关联记录，显示特殊标识
                                if (value == 1) {
                                    return '<span class="label label-danger">缺少食材数据</span>';
                                }
                                return '';
                            }
                        },
                       {
                            field: 'operate',
                            title: __('查看数据及编辑'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: '设置菜品', // 按钮的名称
                                    text: '设置菜品', // 显示的文字
                                    title: '设置菜品',
                                    icon: 'fa fa-video-camera', // 按钮的图标
                                    classname: 'btn btn-xs btn-primary',
                                    // 弹窗对应的后台控制器地址，携带当前行id参数
                                    url: function (row, column) {
                                        return "/gquHAdQcbx.php/food/Ingredientrel?dish_id=" + row.id;
                                    },
                                    // 控制弹窗尺寸（宽度98%，高度98%）
                                    extend:' target="_blank"',
                                    // 弹窗关闭后的回调方法（btn-dialog专用，与btn-ajax的success不同）
                                    callback: function (data) {

                                    },
                                    // 控制按钮显示/隐藏的判断方法
                                    hidden: function (data) {

                                    }
                                }
                            ]
                        }
                    
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            
            // 在表格初始化后添加分类按钮
            setTimeout(function() {
                // 为每个操作列添加分类按钮
                $('tbody tr', table).each(function() {
                    var $tr = $(this);
                    var $operateCell = $tr.find('td:last'); // 操作列一般在最后一列
                    if ($operateCell.find('.btn-categories').length === 0) { // 避免重复添加
                        var rowData = table.bootstrapTable('getData')[$tr.data('index')];
                        if (rowData) {
                            // 添加分类按钮
                            var categoryBtn = '<a href="javascript:;" class="btn btn-xs btn-info btn-categories" data-row="' + Fast.api.escape(JSON.stringify(rowData)) + '" title="分类管理" style="margin-left: 2px;"><i class="fa fa-tags"></i></a>';
                            $operateCell.append(categoryBtn);
                        }
                    }
                });
            }, 100);
            
            // 监听表格刷新事件，在数据加载后重新添加按钮
            table.on('load-success.bs.table', function() {
                setTimeout(function() {
                    $('tbody tr', table).each(function() {
                        var $tr = $(this);
                        var $operateCell = $tr.find('td:last');
                        if ($operateCell.find('.btn-categories').length === 0) {
                            var rowData = table.bootstrapTable('getData')[$tr.data('index')];
                            if (rowData) {
                                // 添加分类按钮
                                var categoryBtn = '<a href="javascript:;" class="btn btn-xs btn-info btn-categories" data-row="' + Fast.api.escape(JSON.stringify(rowData)) + '" title="分类管理" style="margin-left: 2px;"><i class="fa fa-tags"></i></a>';
                                $operateCell.append(categoryBtn);
                            }
                        }
                    });
                }, 50);
            });
            
            // 绑定分类按钮事件
            $(document).off('click', '.btn-categories').on('click', '.btn-categories', function () {
                var row = Fast.api.escape($(this).data("row"), true);
                Controller.api.openCategoriesDialog(row);
            });
        },
        add: function () {
            Controller.api.bindevent();
            // 初始化食材选择功能
            Controller.api.initIngredientSelector();
        },
        edit: function () {
            Controller.api.bindevent();
            // 初始化食材选择功能
            Controller.api.initIngredientSelector();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            
            // 打开分类选择对话框
            openCategoriesDialog: function(row) {
                // 获取分类数据，传递菜品ID用于获取已选择的分类
                Fast.api.ajax({
                    url: 'food/dish/getCategories',
                    type: 'POST',
                    data: {
                        dish_id: row.id
                    }
                }, function(data, ret) {
                    if (ret.code === 1) {
                        Controller.api.showCategoriesDialog(row, data);
                    } else {
                        Toastr.error(ret.msg || '获取分类数据失败');
                    }
                });
            },
            
            // 显示分类选择对话框
            showCategoriesDialog: function(row, data) {
                var content = Controller.api.buildCategoriesContent(data);
                
                Layer.open({
                    type: 1,
                    title: '选择分类 - ' + row.name,
                    area: ['800px', '600px'],
                    content: content,
                    btn: ['保存', '取消'],
                    yes: function(index, layero) {
                        var selectedCategories = Controller.api.getSelectedCategories();

                        
                        // 提交保存分类关联数据
                        Controller.api.saveDishCategories(row.id, selectedCategories, index);
                    },
                    btn2: function(index, layero) {
                        Layer.close(index);
                    },
                    success: function(layero, index) {
                        // 绑定分类联动事件
                        Controller.api.bindCategoryEvents();
                        
                        // 恢复已选择的分类状态
                        if (data.selected) {
                            Controller.api.restoreSelectedCategories(data.selected);
                        }
                    }
                });
            },
            
            // 构建分类选择内容
            buildCategoriesContent: function(data) {
                var html = '<div class="categories-container" style="padding: 20px; max-height: 500px; overflow-y: auto;">';
                
                var categories = [
                    {key: 'crowd', title: '人群分类', data: data.crowd || []},
                    {key: 'cuisine', title: '菜系分类', data: data.cuisine || []},
                    {key: 'form', title: '食材形态', data: data.form || []},
                    {key: 'nutrition', title: '营养分类', data: data.nutrition || []},
                    {key: 'period', title: '时段分类', data: data.period || []},
                    {key: 'region', title: '地域分类', data: data.region || []},
                    {key: 'scene', title: '场景分类', data: data.scene || []},
                    {key: 'tech', title: '工艺技术', data: data.tech || []}
                ];
                
                categories.forEach(function(category) {
                    html += '<div class="category-group" style="margin-bottom: 25px; border: 1px solid #ddd; padding: 15px; border-radius: 5px;">';
                    html += '<h4 style="margin-top: 0; color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">' + category.title + '</h4>';
                    
                    if (category.data && category.data.length > 0) {
                        // 按父级分组
                        var grouped = Controller.api.groupByParent(category.data);
                        
                        // 显示一级分类及其下二级分类
                        if (grouped[0] && grouped[0].length > 0) {
                            grouped[0].forEach(function(parentItem) {
                                // 显示一级分类
                                html += '<div class="parent-category" style="margin-bottom: 15px;">';
                                html += '<label style="display: block; margin-bottom: 8px; font-weight: bold; cursor: pointer;">';
                                html += '<input type="checkbox" class="category-check parent-check" data-category="' + category.key + '" data-level="1" data-parent-id="' + parentItem.id + '" value="' + parentItem.id + '" style="margin-right: 8px;"> ';
                                html += '<span style="color: #2c3e50; font-size: 14px;">' + parentItem.name + '</span>';
                                html += '</label>';
                                
                                // 显示该一级分类下的二级分类
                                if (grouped[parentItem.id] && grouped[parentItem.id].length > 0) {
                                    html += '<div class="child-categories" style="margin-left: 25px; padding: 8px; background-color: #f8f9fa; border-radius: 4px;">';
                                    grouped[parentItem.id].forEach(function(childItem) {
                                        html += '<label style="display: inline-block; margin: 3px 8px 3px 0; cursor: pointer;">';
                                        html += '<input type="checkbox" class="category-check child-check" data-category="' + category.key + '" data-level="2" data-parent-id="' + parentItem.id + '" value="' + childItem.id + '" style="margin-right: 5px;"> ';
                                        html += '<span style="color: #495057;">' + childItem.name + '</span>';
                                        html += '</label>';
                                    });
                                    html += '</div>';
                                }
                                
                                html += '</div>';
                            });
                        }
                        
                        // 显示没有父级的单独分类（如果有）
                        Object.keys(grouped).forEach(function(parentId) {
                            // 确保grouped[0]存在且是一个数组，然后再调用find方法
                            var hasParentInRoot = grouped[0] && Array.isArray(grouped[0]) ? 
                                grouped[0].find(function(item) { return item.id == parentId; }) : 
                                null;
                                
                            if (parentId !== '0' && !hasParentInRoot) {
                                if (grouped[parentId] && grouped[parentId].length > 0) {
                                    html += '<div class="orphan-categories" style="margin-bottom: 10px;">';
                                    html += '<strong style="color: #6c757d;">其他分类：</strong><br>';
                                    grouped[parentId].forEach(function(item) {
                                        html += '<label style="display: inline-block; margin: 3px 8px 3px 0; cursor: pointer;">';
                                        html += '<input type="checkbox" class="category-check" data-category="' + category.key + '" data-level="2" data-parent-id="' + parentId + '" value="' + item.id + '" style="margin-right: 5px;"> ';
                                        html += item.name;
                                        html += '</label>';
                                    });
                                    html += '</div>';
                                }
                            }
                        });
                    } else {
                        html += '<p style="color: #999; font-style: italic;">暂无数据</p>';
                    }
                    
                    html += '</div>';
                });
                
                html += '</div>';
                return html;
            },
            
            // 按父级分组
            groupByParent: function(data) {
                var grouped = {};
                data.forEach(function(item) {
                    // 确保parent_id是整数类型，避免字符串和数字比较失败
                    var parentId = parseInt(item.parent_id) || 0;
                    if (!grouped[parentId]) {
                        grouped[parentId] = [];
                    }
                    grouped[parentId].push(item);
                });
                return grouped;
            },
            
            // 绑定分类联动事件
            bindCategoryEvents: function() {
                // 一级分类点击事件（联动二级分类）
                $(document).off('change', '.parent-check').on('change', '.parent-check', function() {
                    var $this = $(this);
                    var isChecked = $this.prop('checked');
                    var parentId = $this.data('parent-id');
                    var category = $this.data('category');
                    
                    // 联动选中/取消该一级分类下的所有二级分类
                    $('.child-check[data-category="' + category + '"][data-parent-id="' + parentId + '"]').prop('checked', isChecked);
                });
                
                // 二级分类点击事件（联动一级分类）
                $(document).off('change', '.child-check').on('change', '.child-check', function() {
                    var $this = $(this);
                    var parentId = $this.data('parent-id');
                    var category = $this.data('category');
                    
                    // 检查该父级下的所有二级分类是否都被选中
                    var $childChecks = $('.child-check[data-category="' + category + '"][data-parent-id="' + parentId + '"]');
                    var $checkedChildren = $childChecks.filter(':checked');
                    var $parentCheck = $('.parent-check[data-category="' + category + '"][data-parent-id="' + parentId + '"]');
                    
                    if ($checkedChildren.length > 0) {
                        // 有二级分类被选中，选中一级分类
                        $parentCheck.prop('checked', true);
                    } else {
                        // 没有二级分类被选中，取消一级分类
                        $parentCheck.prop('checked', false);
                    }
                });
            },
            
            // 恢复已选择的分类状态
            restoreSelectedCategories: function(selectedData) {
                if (!selectedData) return;
                
                // 遍历所有分类类型
                Object.keys(selectedData).forEach(function(categoryKey) {
                    var ids = selectedData[categoryKey];
                    if (ids && ids.length > 0) {
                        var categoryName = categoryKey.replace('_ids', ''); // 去掉_ids后缀
                        
                        // 选中对应的复选框
                        ids.forEach(function(id) {
                            $('.category-check[data-category="' + categoryName + '"][value="' + id + '"]').prop('checked', true);
                        });
                    }
                });
                

            },
            
            // 获取选中的分类（规范命名用于数据库提交）
            getSelectedCategories: function() {
                var selected = {
                    crowd_ids: [],      // 人群分类ID数组
                    cuisine_ids: [],    // 菜系分类ID数组
                    form_ids: [],       // 食材形态ID数组
                    nutrition_ids: [],  // 营养分类ID数组
                    period_ids: [],     // 时段分类ID数组
                    region_ids: [],     // 地域分类ID数组
                    scene_ids: [],      // 场景分类ID数组
                    tech_ids: []        // 工艺技术ID数组
                };
                
                $('.category-check:checked').each(function() {
                    var $this = $(this);
                    var category = $this.data('category');
                    var value = parseInt($this.val());
                    
                    // 根据分类类型添加到对应的数组
                    switch(category) {
                        case 'crowd':
                            if (selected.crowd_ids.indexOf(value) === -1) {
                                selected.crowd_ids.push(value);
                            }
                            break;
                        case 'cuisine':
                            if (selected.cuisine_ids.indexOf(value) === -1) {
                                selected.cuisine_ids.push(value);
                            }
                            break;
                        case 'form':
                            if (selected.form_ids.indexOf(value) === -1) {
                                selected.form_ids.push(value);
                            }
                            break;
                        case 'nutrition':
                            if (selected.nutrition_ids.indexOf(value) === -1) {
                                selected.nutrition_ids.push(value);
                            }
                            break;
                        case 'period':
                            if (selected.period_ids.indexOf(value) === -1) {
                                selected.period_ids.push(value);
                            }
                            break;
                        case 'region':
                            if (selected.region_ids.indexOf(value) === -1) {
                                selected.region_ids.push(value);
                            }
                            break;
                        case 'scene':
                            if (selected.scene_ids.indexOf(value) === -1) {
                                selected.scene_ids.push(value);
                            }
                            break;
                        case 'tech':
                            if (selected.tech_ids.indexOf(value) === -1) {
                                selected.tech_ids.push(value);
                            }
                            break;
                    }
                });
                
                return selected;
            },
            
            // 保存菜品分类关联数据
            saveDishCategories: function(dishId, selectedCategories, layerIndex) {
                Fast.api.ajax({
                    url: 'food/dish/saveCategories',
                    type: 'POST',
                    data: {
                        dish_id: dishId,
                        categories: JSON.stringify(selectedCategories)
                    }
                }, function(data, ret) {
                    if (ret.code === 1) {
                        Layer.close(layerIndex);
                        // 刷新表格数据
                        $("#table").bootstrapTable('refresh');
                    } else {
                        Toastr.error(ret.msg || '保存失败');
                    }
                }, function(data, ret) {
                    Toastr.error(ret.msg || '保存失败');
                });
            },
            
            // 初始化食材选择器
            initIngredientSelector: function() {
                // 绑定食材选择按钮事件
                $(document).off('click', '#btn-select-ingredients').on('click', '#btn-select-ingredients', function() {
                    Controller.api.openIngredientsDialog();
                });
                
                // 初始化表格事件绑定
                Controller.api.bindIngredientsTableEvents();
                
                // 恢复已选择的食材（如果有）
                var ingredientData = $('#c-ingredient-data').val();
                

                
                // 检查数据是否被截断
                if (ingredientData) {

                }
                
                if (ingredientData && ingredientData.trim() !== '' && ingredientData.trim() !== '[]') {
                    try {
                        // 直接解析JSON数据
                        var data = JSON.parse(ingredientData);
                        // 数据解析成功
                        
                        if (data && Array.isArray(data) && data.length > 0) {

                            
                            // 初始化全局选择状态
                            window.selectedIngredients = {};
                            
                            // 重建全局选择状态
                            data.forEach(function(ingredient, index) {

                                if (ingredient && ingredient.id) {
                                    window.selectedIngredients[ingredient.id] = {
                                        id: ingredient.id,
                                        name: ingredient.name || '',
                                        quantity: ingredient.quantity || 100,
                                        unitEnergy: ingredient.unitEnergy || 0
                                    };
                                } else {

                                }
                            });
                            

                            
                            // 立即更新表格显示
                            var selectedIngredients = Controller.api.getAllSelectedIngredients();

                            Controller.api.updateSelectedIngredients(selectedIngredients);
                            
                            // 强制显示表格
                            if (selectedIngredients.length > 0) {
                                $('#selected-ingredients-table').show();

                            }
                        } else {

                        }
                    } catch (e) {

                    }
                } else {

                }
            },
            
            // 打开食材选择对话框
            openIngredientsDialog: function() {
                Fast.api.ajax({
                    url: 'food/dish/getIngredients',
                    type: 'POST'
                }, function(data, ret) {
                    if (ret.code === 1) {
                        Controller.api.showIngredientsDialog(data);
                    } else {
                        Toastr.error(ret.msg || '获取食材数据失败');
                    }
                });
            },
            
            // 显示食材选择对话框
            showIngredientsDialog: function(data) {
                var content = Controller.api.buildIngredientsContent(data);
                
                // 全局变量存储已选择的食材
                if (typeof window.selectedIngredients === 'undefined') {
                    window.selectedIngredients = {}; // 使用对象存储，key为ID，value为食材信息
                }
                
                Layer.open({
                    type: 1,
                    title: '选择食材',
                    area: ['900px', '700px'],
                    content: content,
                    btn: ['确定', '取消'],
                    yes: function(index, layero) {
                        var selectedIngredients = Controller.api.getAllSelectedIngredients();
                        Controller.api.updateSelectedIngredients(selectedIngredients);
                        Layer.close(index);
                    },
                    btn2: function(index, layero) {
                        Layer.close(index);
                    },
                    success: function(layero, index) {
    
                        
                        // 立即绑定分类点击事件（因为使用document委托，不需要延迟）
                        Controller.api.bindCategoryClickEvents();
                        
                        // 绑定食材选择事件
                        Controller.api.bindIngredientEvents();
                        
                        // 恢复已选择的食材
                        Controller.api.restoreSelectedIngredients();
                        
                        // 默认显示已选择的食材（如果有的话）
                        Controller.api.showSelectedIngredientsOnOpen();
                        
                        // 初始化时更新分类计数显示
                        Controller.api.updateCategoryCount();
                        

                    }
                });
            },
            
            // 构建食材选择内容
            buildIngredientsContent: function(data) {
                var html = '<div class="ingredients-container" style="padding: 20px; max-height: 600px; overflow-y: auto;">';
                
                // 搜索框
                html += '<div class="search-container" style="margin-bottom: 20px;">';
                html += '<div class="row">';
                html += '<div class="col-md-6">';
                html += '<input type="text" id="category-search" class="form-control" placeholder="搜索食材分类（支持拼音简写）">';
                html += '</div>';
                html += '<div class="col-md-6">';
                html += '<input type="text" id="ingredient-search" class="form-control" placeholder="搜索食材（支持拼音简写）" disabled>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
                
                html += '<div class="row">';
                
                // 左侧：食材分类列表
                html += '<div class="col-md-4">';
                html += '<div class="panel panel-default">';
                html += '<div class="panel-heading"><strong>食材分类</strong></div>';
                html += '<div class="panel-body" style="padding: 0; max-height: 400px; overflow-y: auto;">';
                html += '<ul class="list-group" id="categories-list">';
                
                if (data.categories && data.categories.length > 0) {
                    // 按父级分组分类
                    var groupedCategories = {};
                    var parentCategories = [];
                    
                    // 第一次遍历：先初始化所有一级分类
                    data.categories.forEach(function(category) {
                        // 确保parent_id是整数类型
                        var parentId = parseInt(category.parent_id) || 0;
                        if (parentId === 0) {
                            parentCategories.push(category);
                            groupedCategories[category.id] = [];
                        }
                    });
                    
                    // 第二次遍历：添加二级分类到对应的一级分类下
                    data.categories.forEach(function(category) {
                        // 确保parent_id是整数类型
                        var parentId = parseInt(category.parent_id) || 0;
                        if (parentId !== 0) {
                            // 确保父级分类对象存在
                            if (!groupedCategories[parentId]) {
                                groupedCategories[parentId] = [];
                            }
                            groupedCategories[parentId].push(category);
                        }
                    });
                    
                    // 渲染一级分类
                    parentCategories.forEach(function(parentCategory) {
                        var hasChildren = groupedCategories[parentCategory.id] && groupedCategories[parentCategory.id].length > 0;
                        
                        html += '<li class="list-group-item parent-category-item" data-id="' + parentCategory.id + '" data-pinyin="' + (parentCategory.pinyin || '') + '" style="cursor: pointer; border-left: 3px solid transparent; font-weight: bold;">';
                        
                        if (hasChildren) {
                            html += '<i class="fa fa-folder text-warning expand-icon" style="margin-right: 5px;"></i> ';
                        } else {
                            html += '<i class="fa fa-file-o text-muted" style="margin-right: 5px;"></i> ';
                        }
                        
                        html += parentCategory.name;
                        
                        if (hasChildren) {
                            html += ' <small class="text-muted">(' + groupedCategories[parentCategory.id].length + '个子分类)</small>';
                        }
                        
                        html += '</li>';
                        
                        // 二级分类（默认隐藏）
                        if (hasChildren) {
                            html += '<ul class="child-categories" data-parent-id="' + parentCategory.id + '" style="display: none; list-style: none; padding-left: 0; margin: 0;">';
                            groupedCategories[parentCategory.id].forEach(function(childCategory) {
                                html += '<li class="list-group-item child-category-item" data-id="' + childCategory.id + '" data-parent-id="' + parentCategory.id + '" data-pinyin="' + (childCategory.pinyin || '') + '" style="cursor: pointer; border-left: 3px solid transparent; padding-left: 30px; font-weight: normal; background-color: #f9f9f9;">';
                                html += '<i class="fa fa-file text-info" style="margin-right: 5px;"></i> ' + childCategory.name;
                                html += '</li>';
                            });
                            html += '</ul>';
                        }
                    });
                } else {
                    html += '<li class="list-group-item text-muted">暂无分类数据</li>';
                }
                
                html += '</ul>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
                
                // 右侧：食材列表
                html += '<div class="col-md-8">';
                html += '<div class="panel panel-default">';
                html += '<div class="panel-heading">';
                html += '<strong>食材列表</strong> ';
                html += '<span id="selected-category-name" class="text-info"></span>';
                html += '<span id="selected-count" class="pull-right text-success" style="font-weight: normal;"></span>';
                html += '</div>';
                html += '<div class="panel-body" style="padding: 10px; max-height: 400px; overflow-y: auto;">';
                html += '<div id="ingredients-list" class="text-muted text-center" style="padding: 50px 0;">请先选择食材分类</div>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
                
                html += '</div>';
                html += '</div>';
                
                return html;
            },
            
            // 绑定分类点击事件（单独的方法确保正确绑定）
            bindCategoryClickEvents: function() {

                
                // 使用更安全的事件委托绑定方式
                // 一级分类点击事件 - 使用document进行事件委托
                $(document).off('click.parentCategory').on('click.parentCategory', '.parent-category-item', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var $this = $(this);
                    var parentId = $this.data('id');
                    var $children = $('.child-categories[data-parent-id="' + parentId + '"]');
                    var $icon = $this.find('.expand-icon');
                    

                    
                    if ($children.length > 0) {
                        // 有子分类，展开/折叠并加载所有子分类的食材
                        if ($children.is(':visible')) {
                            // 折叠
                            $children.slideUp(200);
                            $icon.removeClass('fa-folder-open').addClass('fa-folder');

                            
                            // 清空右侧内容
                            $('#selected-category-name').text('');
                            $('#ingredient-search').prop('disabled', true).attr('placeholder', '请先选择具体的食材分类');
                            $('#ingredients-list').html('<div class="text-muted text-center" style="padding: 50px 0;">请选择具体的食材分类</div>');
                        } else {
                            // 展开并加载一级分类下所有子分类的食材
                            $('.child-categories').slideUp(200); // 先折叠其他分类
                            $('.parent-category-item .expand-icon').removeClass('fa-folder-open').addClass('fa-folder');
                            
                            $children.slideDown(200);
                            $icon.removeClass('fa-folder').addClass('fa-folder-open');

                            
                            // 更新选中状态
                            $('.child-category-item').removeClass('active').css({
                                'border-left-color': 'transparent',
                                'background-color': '#f9f9f9',
                                'color': ''
                            });
                            $('.parent-category-item').removeClass('active').css({
                                'border-left-color': 'transparent',
                                'background-color': '',
                                'color': ''
                            });
                            $this.addClass('active').css({
                                'border-left-color': '#337ab7',
                                'background-color': '#337ab7',
                                'color': 'white'
                            });
                            
                            var categoryName = $this.text().trim().replace(/\(\d+个子分类\)/, '').trim();
                            $('#selected-category-name').text('- ' + categoryName + ' (所有子分类)');
                            $('#ingredient-search').prop('disabled', false).attr('placeholder', '搜索 ' + categoryName + ' 中的食材（支持拼音简写）');
                            
                            // 加载该一级分类下所有子分类的食材
                            Controller.api.loadIngredientsByParentCategory(parentId);
                            
                            // 展开后更新二级分类的计数显示
                            Controller.api.updateCategoryCount();
                        }
                    } else {
                        // 没有子分类的一级分类，尝试直接加载食材（如果有的话）

                        
                        // 更新选中状态
                        $('.child-category-item').removeClass('active').css({
                            'border-left-color': 'transparent',
                            'background-color': '#f9f9f9',
                            'color': ''
                        });
                        $('.parent-category-item').removeClass('active').css({
                            'border-left-color': 'transparent',
                            'background-color': '',
                            'color': ''
                        });
                        $this.addClass('active').css({
                            'border-left-color': '#337ab7',
                            'background-color': '#337ab7',
                            'color': 'white'
                        });
                        
                        var categoryName = $this.text().trim().replace(/\(\d+个子分类\)/, '').trim();
                        $('#selected-category-name').text('- ' + categoryName);
                        $('#ingredient-search').prop('disabled', false).attr('placeholder', '搜索 ' + categoryName + ' 中的食材（支持拼音简写）');
                        
                        // 尝试加载该一级分类下的食材
                        Controller.api.loadIngredientsByCategory(parentId);
                    }
                });
                
                // 二级分类点击事件 - 使用document进行事件委托
                $(document).off('click.childCategory').on('click.childCategory', '.child-category-item', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var $this = $(this);
                    var categoryId = $this.data('id');
                    var categoryName = $this.text().trim();
                    

                    
                    // 更新选中状态 - 改为蓝色背景
                    $('.child-category-item').removeClass('active').css({
                        'border-left-color': 'transparent',
                        'background-color': '#f9f9f9',
                        'color': ''
                    });
                    $('.parent-category-item').removeClass('active').css({
                        'border-left-color': 'transparent',
                        'background-color': '',
                        'color': ''
                    });
                    $this.addClass('active').css({
                        'border-left-color': '#337ab7',
                        'background-color': '#337ab7',
                        'color': 'white'
                    });
                    
                    // 更新标题
                    $('#selected-category-name').text('- ' + categoryName);
                    
                    // 启用食材搜索框
                    $('#ingredient-search').prop('disabled', false).attr('placeholder', '搜索 ' + categoryName + ' 中的食材（支持拼音简写）');
                    
                    // 加载该二级分类下的食材
                    Controller.api.loadIngredientsByCategory(categoryId);
                });
                

            },
            
            // 获取当前选中的分类ID
            getCurrentCategoryId: function() {
                var $activeCategory = $('.parent-category-item.active, .child-category-item.active');
                return $activeCategory.length > 0 ? $activeCategory.data('id') : null;
            },
            
            // 显示打开对话框时的已选食材
            showSelectedIngredientsOnOpen: function() {
                // 如果有已选择的食材，显示详细的食材列表
                if (window.selectedIngredients && Object.keys(window.selectedIngredients).length > 0) {
                    var html = '';
                    var count = Object.keys(window.selectedIngredients).length;
                    
                    html += '<div class="selected-ingredients-summary" style="padding: 15px; background-color: #f0f8ff; border-radius: 5px; margin-bottom: 10px;">';
                    html += '<h5 style="margin-bottom: 15px; color: #2c3e50;">已选择的食材 (' + count + '个)</h5>';
                    
                    // 检查是否有食材缺少分类ID
                    var hasIngredientsWithoutCategory = false;
                    for (var id in window.selectedIngredients) {
                        if (!window.selectedIngredients[id].categoryId) {
                            hasIngredientsWithoutCategory = true;
                            break;
                        }
                    }
                    
                    // 使用类似右侧食材选中的样式
                    for (var id in window.selectedIngredients) {
                        var ingredient = window.selectedIngredients[id];
                        var quantity = ingredient.quantity || 100;
                        var unitEnergy = ingredient.unitEnergy || 0;
                        
                        html += '<div class="ingredient-item selected" style="margin-bottom: 8px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; cursor: default; background-color: #f0f8ff; border-left: 3px solid #337ab7;">';
                        html += '<span class="ingredient-name" style="font-weight: bold; color: #2c3e50;">' + ingredient.name + '</span>';
                        html += ' <small class="text-muted">(' + quantity.toFixed(2) + 'g)</small>';
                        html += ' <small class="text-info">' + unitEnergy + '千卡/100g</small>';
                        html += '</div>';
                    }
                    
                    html += '<p class="text-muted" style="margin-top: 15px; margin-bottom: 0; font-style: italic;">💡 提示：请选择左侧分类来添加更多食材或重新选择</p>';
                    
                    // 如果有食材缺少分类ID，显示额外提示
                    if (hasIngredientsWithoutCategory) {
                        html += '<div class="alert alert-warning" style="margin-top: 10px; margin-bottom: 0; padding: 10px; font-size: 12px;">';
                        html += '<i class="fa fa-exclamation-triangle"></i> 部分食材缺少分类信息，将不会在左侧分类上显示计数。<br>';
                        html += '解决方案：点击左侧对应的二级分类，系统会自动修复相关食材的分类信息。';
                        html += '</div>';
                    }
                    html += '</div>';
                    
                    $('#ingredients-list').html(html);
                }
            },
            
            // 绑定食材选择事件
            bindIngredientEvents: function() {
                // 分类搜索
                $(document).off('input', '#category-search').on('input', '#category-search', function() {
                    var keyword = $(this).val().toLowerCase();
                    
                    if (keyword.trim() === '') {
                        // 清空搜索时显示所有分类，折叠二级分类
                        $('.parent-category-item').show();
                        $('.child-categories').hide();
                        $('.parent-category-item .expand-icon').removeClass('fa-folder-open').addClass('fa-folder');
                        
                        // 清除所有选中状态
                        $('.parent-category-item, .child-category-item').removeClass('active').css({
                            'border-left-color': 'transparent',
                            'background-color': '',
                            'color': ''
                        });
                        $('.child-category-item').css('background-color', '#f9f9f9');
                        
                        // 清空标题和禁用搜索框
                        $('#selected-category-name').text('');
                        $('#ingredient-search').prop('disabled', true).attr('placeholder', '请先选择食材分类');
                        $('#ingredients-list').html('<div class="text-muted text-center" style="padding: 50px 0;">请先选择食材分类</div>');
                    } else {
                        // 搜索一级分类
                        $('.parent-category-item').each(function() {
                            var $item = $(this);
                            var name = $item.text().toLowerCase();
                            var pinyin = $item.data('pinyin') ? $item.data('pinyin').toLowerCase() : '';
                            var parentId = $item.data('id');
                            var $children = $('.child-categories[data-parent-id="' + parentId + '"]');
                            
                            var parentMatched = name.indexOf(keyword) >= 0 || pinyin.indexOf(keyword) >= 0;
                            var childMatched = false;
                            
                            // 检查二级分类是否匹配
                            if ($children.length > 0) {
                                $children.find('.child-category-item').each(function() {
                                    var $child = $(this);
                                    var childName = $child.text().toLowerCase();
                                    var childPinyin = $child.data('pinyin') ? $child.data('pinyin').toLowerCase() : '';
                                    
                                    if (childName.indexOf(keyword) >= 0 || childPinyin.indexOf(keyword) >= 0) {
                                        childMatched = true;
                                        $child.show();
                                    } else {
                                        $child.hide();
                                    }
                                });
                            }
                            
                            if (parentMatched || childMatched) {
                                $item.show();
                                if (childMatched && $children.length > 0) {
                                    // 如果二级分类匹配，展开显示
                                    $children.show();
                                    $item.find('.expand-icon').removeClass('fa-folder').addClass('fa-folder-open');
                                }
                            } else {
                                $item.hide();
                                $children.hide();
                            }
                        });
                    }
                });
                
                // 食材搜索
                $(document).off('input', '#ingredient-search').on('input', '#ingredient-search', function() {
                    var keyword = $(this).val().toLowerCase();
                    $('.ingredient-item').each(function() {
                        var $item = $(this);
                        var name = $item.find('.ingredient-name').text().toLowerCase();
                        var pinyin = $item.data('pinyin') ? $item.data('pinyin').toLowerCase() : '';
                        
                        if (name.indexOf(keyword) >= 0 || pinyin.indexOf(keyword) >= 0) {
                            $item.show();
                        } else {
                            $item.hide();
                        }
                    });
                });
                
                // 食材选择事件
                $(document).off('change', '.ingredient-checkbox').on('change', '.ingredient-checkbox', function() {
                    var $checkbox = $(this);
                    var $item = $checkbox.closest('.ingredient-item');
                    var ingredientId = parseInt($checkbox.val());
                    var ingredientName = $item.find('.ingredient-name').text();
                    
                    // 获取食材的详细信息
                    var weight = $item.data('weight') || 100; // 默认100g
                    var energy = $item.data('energy') || 0; // 能量(千卡/100g)
                    
                    if ($checkbox.prop('checked')) {
                        $item.addClass('selected').css('background-color', '#f0f8ff');
                        // 添加到全局选择列表
                        window.selectedIngredients[ingredientId] = {
                            id: ingredientId,
                            name: ingredientName,
                            weight: weight, // 默认重量
                            unitEnergy: energy, // 单位能量(千卡/100g)
                            quantity: 100, // 用户设置的重量
                            categoryId: Controller.api.getCurrentCategoryId() // 保存当前分类ID
                        };
                    } else {
                        $item.removeClass('selected').css('background-color', '');
                        // 从全局选择列表中移除
                        delete window.selectedIngredients[ingredientId];
                    }
                    
                    // 更新选中数量显示
                    Controller.api.updateSelectedCount();
                    
                    // 实时更新分类计数显示
                    Controller.api.updateCategoryCount();
                });
            },
            
            // 根据分类加载食材
            loadIngredientsByCategory: function(categoryId) {
                $('#ingredients-list').html('<div class="text-center" style="padding: 50px 0;"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
                
                Fast.api.ajax({
                    url: 'food/dish/getIngredientsByCategory',
                    type: 'POST',
                    data: { category_id: categoryId }
                }, function(data, ret) {
                    if (ret.code === 1) {
                        // 在渲染之前，检查并修复已选食材的分类ID
                        Controller.api.fixSelectedIngredientsCategoryId(categoryId, data.ingredients);
                        
                        Controller.api.renderIngredientsList(data.ingredients);
                    } else {
                        $('#ingredients-list').html('<div class="text-center text-danger" style="padding: 50px 0;">加载失败: ' + (ret.msg || '未知错误') + '</div>');
                    }
                });
            },
            
            // 修复已选食材的分类ID
            fixSelectedIngredientsCategoryId: function(categoryId, ingredients) {
                if (!window.selectedIngredients || !ingredients) {
                    return;
                }
                
                var fixedCount = 0;
                
                // 遍历当前分类下的所有食材
                ingredients.forEach(function(ingredient) {
                    var ingredientId = ingredient.id;
                    
                    // 如果该食材已被选中但没有分类ID，则补充分类ID
                    if (window.selectedIngredients[ingredientId] && !window.selectedIngredients[ingredientId].categoryId) {
                        window.selectedIngredients[ingredientId].categoryId = categoryId;
                        fixedCount++;

                    }
                });
                
                if (fixedCount > 0) {

                    
                    // 更新隐藏字段，保存修复后的数据
                    Controller.api.updateHiddenFields();
                    
                    // 更新分类计数显示
                    Controller.api.updateCategoryCount();
                }
            },
            
            // 根据一级分类加载所有子分类的食材
            loadIngredientsByParentCategory: function(parentCategoryId) {
                $('#ingredients-list').html('<div class="text-center" style="padding: 50px 0;"><i class="fa fa-spinner fa-spin"></i> 加载中...</div>');
                
                Fast.api.ajax({
                    url: 'food/dish/getIngredientsByParentCategory',
                    type: 'POST',
                    data: { parent_category_id: parentCategoryId }
                }, function(data, ret) {
                    if (ret.code === 1) {
                        // 在渲染之前，检查并修复已选食材的分类ID
                        if (data.ingredients && data.ingredients.length > 0) {
                            data.ingredients.forEach(function(ingredient) {
                                if (ingredient.category_id) {
                                    Controller.api.fixSelectedIngredientsCategoryId(ingredient.category_id, [ingredient]);
                                }
                            });
                        }
                        
                        Controller.api.renderParentCategoryIngredientsList(data.ingredients || [], parentCategoryId);
                    } else {
                        $('#ingredients-list').html('<div class="text-center text-danger" style="padding: 50px 0;">加载失败: ' + (ret.msg || '未知错误') + '</div>');
                    }
                });
            },
            
            // 渲染一级分类下的所有食材（按子分类分组）
            renderParentCategoryIngredientsList: function(ingredients, parentCategoryId) {
                var html = '';
                
                if (ingredients && ingredients.length > 0) {
                    // 按子分类分组
                    var groupedByCategory = {};
                    var categoryNames = {};
                    
                    ingredients.forEach(function(ingredient) {
                        var categoryId = ingredient.category_id || 'unknown';
                        var categoryName = ingredient.category_name || '未分类';
                        
                        if (!groupedByCategory[categoryId]) {
                            groupedByCategory[categoryId] = [];
                            categoryNames[categoryId] = categoryName;
                        }
                        groupedByCategory[categoryId].push(ingredient);
                    });
                    
                    // 渲染各个子分类及其食材
                    Object.keys(groupedByCategory).forEach(function(categoryId) {
                        var categoryIngredients = groupedByCategory[categoryId];
                        var categoryName = categoryNames[categoryId];
                        
                        // 子分类标题
                        html += '<div class="category-section" style="margin-bottom: 20px;">';
                        html += '<h6 style="background-color: #f5f5f5; padding: 8px 12px; margin: 0 0 10px 0; border-left: 3px solid #337ab7; font-weight: bold;">';
                        html += '<i class="fa fa-tag" style="margin-right: 5px;"></i>' + categoryName + ' (' + categoryIngredients.length + '个)';
                        html += '</h6>';
                        
                        // 该子分类下的食材
                        categoryIngredients.forEach(function(ingredient) {
                            // 检查是否已经被选中
                            var isSelected = window.selectedIngredients && window.selectedIngredients[ingredient.id];
                            var checkedAttr = isSelected ? 'checked' : '';
                            var selectedClass = isSelected ? 'selected' : '';
                            var backgroundColor = isSelected ? 'background-color: #f0f8ff;' : '';
                            
                            html += '<div class="ingredient-item ' + selectedClass + '" data-id="' + ingredient.id + '" data-weight="' + (ingredient.weight || 100) + '" data-energy="' + (ingredient.energy_kilocalorie || 0) + '" data-pinyin="' + (ingredient.pinyin || '') + '" style="margin-bottom: 6px; margin-left: 15px; padding: 6px; border: 1px solid #ddd; border-radius: 3px; cursor: pointer; ' + backgroundColor + '">';
                            html += '<label style="margin: 0; cursor: pointer; width: 100%;">';
                            html += '<input type="checkbox" class="ingredient-checkbox" value="' + ingredient.id + '" ' + checkedAttr + ' style="margin-right: 6px;">';
                            html += '<span class="ingredient-name">' + ingredient.name + '</span>';
                            if (ingredient.weight) {
                                html += ' <small class="text-muted">(' + ingredient.weight + 'g)</small>';
                            }
                            if (ingredient.energy_kilocalorie) {
                                html += ' <small class="text-info">' + ingredient.energy_kilocalorie + '千卡/100g</small>';
                            }
                            html += '</label>';
                            html += '</div>';
                        });
                        
                        html += '</div>';
                    });
                } else {
                    html = '<div class="text-center text-muted" style="padding: 50px 0;">该分类下暂无食材</div>';
                }
                
                $('#ingredients-list').html(html);
                
                // 更新选中数量显示
                Controller.api.updateSelectedCount();
            },

            // 渲染食材列表
            renderIngredientsList: function(ingredients) {
                var html = '';
                
                if (ingredients && ingredients.length > 0) {
                    ingredients.forEach(function(ingredient) {
                        // 检查是否已经被选中
                        var isSelected = window.selectedIngredients && window.selectedIngredients[ingredient.id];
                        var checkedAttr = isSelected ? 'checked' : '';
                        var selectedClass = isSelected ? 'selected' : '';
                        var backgroundColor = isSelected ? 'background-color: #f0f8ff;' : '';
                        
                        html += '<div class="ingredient-item ' + selectedClass + '" data-id="' + ingredient.id + '" data-weight="' + (ingredient.weight || 100) + '" data-energy="' + (ingredient.energy_kilocalorie || 0) + '" data-pinyin="' + (ingredient.pinyin || '') + '" style="margin-bottom: 8px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; ' + backgroundColor + '">';
                        html += '<label style="margin: 0; cursor: pointer; width: 100%;">';
                        html += '<input type="checkbox" class="ingredient-checkbox" value="' + ingredient.id + '" ' + checkedAttr + ' style="margin-right: 8px;">';
                        html += '<span class="ingredient-name">' + ingredient.name + '</span>';
                        if (ingredient.weight) {
                            html += ' <small class="text-muted">(' + ingredient.weight + 'g)</small>';
                        }
                        if (ingredient.energy_kilocalorie) {
                            html += ' <small class="text-info">' + ingredient.energy_kilocalorie + '千卡/100g</small>';
                        }
                        html += '</label>';
                        html += '</div>';
                    });
                } else {
                    html = '<div class="text-center text-muted" style="padding: 50px 0;">该分类下暂无食材</div>';
                }
                
                $('#ingredients-list').html(html);
                
                // 更新选中数量显示
                Controller.api.updateSelectedCount();
            },
            
            // 获取选中的食材（从全局变量获取）
            getAllSelectedIngredients: function() {
                var selectedIngredients = [];
                if (window.selectedIngredients) {
                    for (var id in window.selectedIngredients) {
                        selectedIngredients.push(window.selectedIngredients[id]);
                    }
                }
                return selectedIngredients;
            },
            
            // 获取当前显示的选中食材（兼容旧方法）
            getSelectedIngredients: function() {
                return Controller.api.getAllSelectedIngredients();
            },
            
            // 更新选中数量显示
            updateSelectedCount: function() {
                var count = 0;
                if (window.selectedIngredients) {
                    count = Object.keys(window.selectedIngredients).length;
                }
                
                var countText = count > 0 ? '已选择 ' + count + ' 个食材' : '';
                $('#selected-count').text(countText);
            },
            
            // 更新分类计数
            updateCategoryCount: function() {
                // 统计已选食材在各个分类中的数量
                if (!window.selectedIngredients) {
                    return;
                }
                
                // 先清空所有分类的计数徽章
                $('.category-count-badge').remove();
                
                // 统计每个分类下已选择的食材数量
                var categoryIngredientCount = {};
                var ingredientsWithoutCategory = 0;
                
                for (var ingredientId in window.selectedIngredients) {
                    var ingredient = window.selectedIngredients[ingredientId];
                    if (ingredient.categoryId) {
                        categoryIngredientCount[ingredient.categoryId] = (categoryIngredientCount[ingredient.categoryId] || 0) + 1;
                    } else {
                        ingredientsWithoutCategory++;
                    }
                }

                if (ingredientsWithoutCategory > 0) {

                }
                
                // 在分类名称后添加徽章显示数量（包括隐藏的二级分类）
                for (var categoryId in categoryIngredientCount) {
                    var count = categoryIngredientCount[categoryId];
                    if (count > 0) {
                        // 在所有二级分类上显示计数徽章（不管是否可见）
                        var $categoryItem = $('.child-category-item[data-id="' + categoryId + '"]');
                        if ($categoryItem.length > 0 && $categoryItem.find('.category-count-badge').length === 0) {
                            $categoryItem.append(' <span class="badge badge-success category-count-badge">' + count + '</span>');

                        }
                    }
                }
            },
            
            // 更新选中的食材显示
            updateSelectedIngredients: function(selectedIngredients) {
                var ids = [];
                var ingredientData = [];
                
                // 更新简单显示
                var names = selectedIngredients.map(function(item) { return item.name; });
                $('#c-selected-ingredients').val(names.join(', '));
                
                // 生成表格数据
                var tableHtml = '';
                var totalWeight = 0;
                var totalEnergy = 0;
                
                selectedIngredients.forEach(function(ingredient) {
                    ids.push(ingredient.id);
                    
                    var quantity = ingredient.quantity || 100;
                    var unitEnergy = ingredient.unitEnergy || 0;
                    var currentEnergy = (unitEnergy * quantity / 100);
                    
                    totalWeight += quantity;
                    totalEnergy += currentEnergy;
                    
                    // 保存食材数据
                    ingredientData.push({
                        id: ingredient.id,
                        name: ingredient.name,
                        quantity: quantity,
                        unitEnergy: unitEnergy,
                        categoryId: ingredient.categoryId // 保存分类ID
                    });
                    
                    tableHtml += '<tr data-ingredient-id="' + ingredient.id + '">';
                    tableHtml += '<td>' + ingredient.name + '</td>';
                    tableHtml += '<td><input type="number" class="form-control input-sm ingredient-quantity" value="' + quantity + '" min="1" max="10000" style="width: 80px;"></td>';
                    tableHtml += '<td class="unit-energy">' + unitEnergy + '</td>';
                    tableHtml += '<td class="total-energy">' + currentEnergy.toFixed(2) + '</td>';
                    tableHtml += '<td><button type="button" class="btn btn-danger btn-xs remove-ingredient" data-id="' + ingredient.id + '"><i class="fa fa-trash"></i></button></td>';
                    tableHtml += '</tr>';
                });
                
                // 更新表格
                $('#ingredients-tbody').html(tableHtml);
                $('#total-weight').text(totalWeight.toFixed(2) + 'g');
                $('#total-energy').text(totalEnergy.toFixed(2) + '千卡');
                
                // 保存数据
                $('#c-ingredient-ids').val(ids.join(','));
                $('#c-ingredient-data').val(JSON.stringify(ingredientData));
                
                if (selectedIngredients.length > 0) {
                    $('#selected-ingredients-table').show();
                } else {
                    $('#selected-ingredients-table').hide();
                }
                
                // 绑定表格事件
                Controller.api.bindIngredientsTableEvents();
            },
            
            // 恢复已选择的食材
            restoreSelectedIngredients: function() {
                // 初始化全局食材选择状态
                if (typeof window.selectedIngredients === 'undefined') {
                    window.selectedIngredients = {};
                }
                
                // 从表单中获取已选择的食材数据
                var ingredientData = $('#c-ingredient-data').val();
                
                if (ingredientData) {
                    try {
                        var data = JSON.parse(ingredientData);

                        // 重建全局选择状态
                        window.selectedIngredients = {};
                        data.forEach(function(ingredient) {
                            var categoryId = ingredient.categoryId || null;
                            
                            // 如果没有分类ID，记录警告
                            if (!categoryId) {

                            }
                            
                            window.selectedIngredients[ingredient.id] = {
                                id: ingredient.id,
                                name: ingredient.name,
                                quantity: ingredient.quantity || 100,
                                unitEnergy: ingredient.unitEnergy || 0,
                                categoryId: categoryId // 保存分类ID，可能为 null
                            };
                        });
                        
                        // 食材数据恢复完成
                    } catch (e) {
                        // 解析食材数据失败
                    }
                }
                
                // 更新选中数量显示
                Controller.api.updateSelectedCount();
            },
            
            // 绑定食材表格事件
            bindIngredientsTableEvents: function() {
                // 重量修改事件
                $(document).off('input', '.ingredient-quantity').on('input', '.ingredient-quantity', function() {
                    var $input = $(this);
                    var quantity = parseFloat($input.val()) || 0;
                    var $row = $input.closest('tr');
                    var ingredientId = parseInt($row.data('ingredient-id'));
                    var unitEnergy = parseFloat($row.find('.unit-energy').text()) || 0;
                    
                    // 计算总能量
                    var totalEnergy = (unitEnergy * quantity / 100);
                    $row.find('.total-energy').text(totalEnergy.toFixed(2));
                    
                    // 更新全局数据
                    if (window.selectedIngredients[ingredientId]) {
                        window.selectedIngredients[ingredientId].quantity = quantity;
                    }
                    
                    // 更新合计
                    Controller.api.updateTotals();
                    
                    // 更新隐藏字段
                    Controller.api.updateHiddenFields();
                });
                
                // 删除食材事件
                $(document).off('click', '.remove-ingredient').on('click', '.remove-ingredient', function() {
                    var ingredientId = parseInt($(this).data('id'));
                    var $row = $(this).closest('tr');
                    
                    // 从全局数据中删除
                    delete window.selectedIngredients[ingredientId];
                    
                    // 删除表格行
                    $row.remove();
                    
                    // 更新合计
                    Controller.api.updateTotals();
                    
                    // 更新选中数量显示
                    Controller.api.updateSelectedCount();
                    
                    // 更新隐藏字段
                    Controller.api.updateHiddenFields();
                    
                    // 如果没有食材了，隐藏表格
                    if (Object.keys(window.selectedIngredients).length === 0) {
                        $('#selected-ingredients-table').hide();
                        $('#c-selected-ingredients').val('');
                    }
                });
            },
            
            // 更新合计
            updateTotals: function() {
                var totalWeight = 0;
                var totalEnergy = 0;
                
                $('#ingredients-tbody tr').each(function() {
                    var $row = $(this);
                    var quantity = parseFloat($row.find('.ingredient-quantity').val()) || 0;
                    var energy = parseFloat($row.find('.total-energy').text()) || 0;
                    
                    totalWeight += quantity;
                    totalEnergy += energy;
                });
                
                $('#total-weight').text(totalWeight.toFixed(2) + 'g');
                $('#total-energy').text(totalEnergy.toFixed(2) + '千卡');
            },
            
            // 更新隐藏字段
            updateHiddenFields: function() {
                var ids = [];
                var ingredientData = [];
                var names = [];
                
                for (var id in window.selectedIngredients) {
                    var ingredient = window.selectedIngredients[id];
                    ids.push(ingredient.id);
                    names.push(ingredient.name);
                    ingredientData.push({
                        id: ingredient.id,
                        name: ingredient.name,
                        quantity: ingredient.quantity,
                        unitEnergy: ingredient.unitEnergy,
                        categoryId: ingredient.categoryId // 保存分类ID
                    });
                }
                
                $('#c-ingredient-ids').val(ids.join(','));
                $('#c-ingredient-data').val(JSON.stringify(ingredientData));
                $('#c-selected-ingredients').val(names.join(', '));
            }
        }
    };
    return Controller;
});